package lib.util;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class HttpUtil {
    /**
     * @param url
     * @param data 生成字符二维码的数据包
     * @return
     *
     */
    public static String sendHttpByPost(String url ,String data ){

        try {
            URL urlPost = new URL(url);
            URLConnection urlConnection = urlPost.openConnection();
            //要发送数据出去，必须设置为可发送状态
            urlConnection.setDoOutput(true);
            //获取输出流
            OutputStream outputStream = urlConnection.getOutputStream();
            //写出数据
            outputStream.write(data.getBytes());
            outputStream.flush();
            outputStream.close();

            //获取输入流
            InputStream is = urlConnection.getInputStream();

            int size ;
            byte[] jsonBytes = new byte[1024];
            StringBuilder stringBuilder = new StringBuilder();
            while ((size=is.read(jsonBytes))!=-1){
                stringBuilder.append(new String(jsonBytes,0,size));
            }
            is.close();
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * @param url
     * @return
     *
     */
    public static String sendHttpByGet(String url){

        try {
            URL urlGet = new URL(url);
            URLConnection urlConnection = urlGet.openConnection();
            InputStream is = urlConnection.getInputStream();
            int size ;
            byte[] jsonBytes = new byte[1024];
            StringBuilder stringBuilder = new StringBuilder();
            while ((size=is.read(jsonBytes))!=-1){
                stringBuilder.append(new String(jsonBytes,0,size));
            }
            is.close();
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}